import {
  ElButton,
  ElCol,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElRadio,
  ElRadioGroup,
  ElRow,
  ElSpace,
  ElTreeSelect,
  type FormInstance,
  type FormRules
} from 'element-plus'
import { computed, defineComponent, reactive, toRefs } from 'vue'

import { deptApi, type IDeptListItem } from '@/apis'
import { objAssign } from '@/utils'

import { useDeptTree } from '../../hooks'
import { deptDialogProps, formData, type IFormData } from './DeptDialog.define'

export default defineComponent({
  name: 'DeptDialog',
  props: deptDialogProps(),
  emits: ['success'],
  setup(_, { emit }) {
    const state = reactive({
      show: false,
      isAdd: true,
      formRef: {} as FormInstance,
      formModel: formData(),
      formRules: {
        parentId: [{ required: true, message: '请选择上级部门' }],
        deptName: [{ required: true, message: '请输入部门名称' }],
        orderNum: [{ required: true, message: '请输入显示顺序' }]
      } as FormRules<IFormData>,
      selectedRecord: {} as IDeptListItem,
      submitLoading: false
    })

    const { getDeptTree, ...deptTreeRestHook } = useDeptTree()

    const dialogTitle = computed(() => (state.isAdd ? '添加部门' : '修改部门'))

    function open(data = {} as Partial<IDeptListItem>, isAdd = true) {
      objAssign(state.formModel, data)
      Object.assign(state.selectedRecord, data)
      state.isAdd = isAdd
      state.show = true

      getDeptTree()
    }

    function handleClose() {
      state.show = false
      state.submitLoading = false
      state.selectedRecord = Object.create(null)
      state.formModel = formData()
      state.formRef.clearValidate()
    }

    function handleSubmit() {
      state.formRef.validate(async valid => {
        if (valid) {
          try {
            state.submitLoading = true

            if (state.isAdd) {
              await deptApi.createDept(state.formModel)
            } else {
              await deptApi.updateDept(state.selectedRecord.id, state.formModel)
            }

            handleClose()
            emit('success')
          } catch (error) {
            state.submitLoading = false
          }
        }
      })
    }

    return {
      ...toRefs(state),
      ...deptTreeRestHook,
      dialogTitle,
      open,
      handleClose,
      handleSubmit
    }
  },
  render() {
    return (
      <ElDialog
        v-model={this.show}
        title={this.dialogTitle}
        width="600px"
        beforeClose={this.handleClose}
        destroyOnClose
      >
        {{
          default: () => (
            <ElForm
              ref={(e: any) => (this.formRef = e)}
              model={this.formModel}
              rules={this.formRules}
              labelWidth="100px"
            >
              <ElRow>
                <ElCol span={24}>
                  <ElFormItem label="上级部门" prop="parentId">
                    <ElTreeSelect
                      v-model={this.formModel.parentId}
                      data={this.deptTree}
                      nodeKey="key"
                      props={{
                        children: 'children',
                        label: 'title'
                      }}
                      placeholder="请选择上级部门"
                      clearable
                      checkStrictly
                      style="width: 100%"
                    />
                  </ElFormItem>
                </ElCol>
              </ElRow>
              <ElRow>
                <ElCol span={12}>
                  <ElFormItem label="部门名称" prop="deptName">
                    <ElInput
                      v-model={this.formModel.deptName}
                      placeholder="请输入部门名称"
                    />
                  </ElFormItem>
                </ElCol>
                <ElCol span={12}>
                  <ElFormItem label="显示顺序" prop="orderNum">
                    <ElInputNumber
                      v-model={this.formModel.orderNum}
                      style="width: 100%"
                    />
                  </ElFormItem>
                </ElCol>
              </ElRow>
              <ElRow>
                <ElCol span={12}>
                  <ElFormItem label="负责人" prop="leader">
                    <ElInput
                      v-model={this.formModel.leader}
                      placeholder="请输入负责人"
                    />
                  </ElFormItem>
                </ElCol>
                <ElCol span={12}>
                  <ElFormItem label="联系电话" prop="phone">
                    <ElInput
                      v-model={this.formModel.phone}
                      placeholder="请输入联系电话"
                    />
                  </ElFormItem>
                </ElCol>
              </ElRow>
              <ElRow>
                <ElCol span={12}>
                  <ElFormItem label="邮箱" prop="email">
                    <ElInput
                      v-model={this.formModel.email}
                      placeholder="请输入邮箱"
                    />
                  </ElFormItem>
                </ElCol>
                <ElCol span={12}>
                  <ElFormItem label="部门状态" prop="status">
                    <ElRadioGroup v-model={this.formModel.status}>
                      {this.statusOptions.map(v => (
                        <ElRadio key={v.value} value={v.value}>
                          {v.label}
                        </ElRadio>
                      ))}
                    </ElRadioGroup>
                  </ElFormItem>
                </ElCol>
              </ElRow>
            </ElForm>
          ),
          footer: () => (
            <ElSpace>
              <ElButton onClick={this.handleClose}>取消</ElButton>
              <ElButton
                type="primary"
                loading={this.submitLoading}
                onClick={this.handleSubmit}
              >
                确定
              </ElButton>
            </ElSpace>
          )
        }}
      </ElDialog>
    )
  }
})
